package com.ttb.bubbles;

import java.util.Iterator;
import java.util.List;
import java.util.Random;

import com.ttb.blocksms.BlockService;
import com.ttb.database.Blocker;
import com.ttb.database.Contact;
import com.ttb.database.ContactDAO;
import com.ttb.database.MessageDAO;
import com.ttb.database.MessageSMS;
import com.ttb.database.Schedule;
import com.ttb.database.ScheduleDAO;
import com.ttb.privatebox.CustomizedListView;
import com.ttb.smshelper.R;
import de.svenjacobs.loremipsum.LoremIpsum;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.ListView;

public class HelloBubblesActivity extends Activity {
	public static DiscussArrayAdapter adapter;
	private ListView lv;
	private EditText editText1;
	private ContactDAO contactDAO;
	private MessageDAO messageDAO;
	private Context context;
	private String contact_id;
	public static HelloBubblesActivity thisActivity = null;
	private BroadcastReceiver smsReceiver;
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		thisActivity = null;
		this.unregisterReceiver(smsReceiver);
		
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		IntentFilter intentFilter = new IntentFilter("SmsMessage.intent.MAIN");
		thisActivity = this;
		smsReceiver = new BroadcastReceiver() {
			
			@Override
			public void onReceive(Context context, Intent intent) {
				Bundle bunble = intent.getExtras();
				String smsBody = bunble.getString(BlockService.SMS_BODY);
				int commingContactId = bunble.getInt(BlockService.CONTACT_ID);
				if(contact_id.equals(String.valueOf(commingContactId)))
				{
					adapter.add(new OneComment(true, smsBody));
					adapter.notifyDataSetChanged();
				}
				
			}
		};
		this.registerReceiver(smsReceiver, intentFilter);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_discuss);
		context = this.getApplicationContext();
		contactDAO = new ContactDAO(context);
		messageDAO = new MessageDAO(context);
		Bundle extras = getIntent().getExtras();
	    if (extras == null) {
	      return;
	    }
	    contact_id = extras.getString(CustomizedListView.KEY_ID);
	    Log.d("contact id", contact_id);
		lv = (ListView) findViewById(R.id.listView1);

		adapter = new DiscussArrayAdapter(getApplicationContext(), R.layout.listitem_discuss);

		lv.setAdapter(adapter);

		editText1 = (EditText) findViewById(R.id.editText1);
		editText1.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// If the event is a key-down event on the "enter" button
				if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
					// Perform action on key press
					adapter.add(new OneComment(false, editText1.getText().toString()));
					String numberPhone = getPhoneNumber(contact_id);
					String message = editText1.getText().toString();
					sendSMS(message, numberPhone);
					editText1.setText("");
					return true;
				}
				return false;
			}
		});
		
		//get phone number from contact id
		
		addItems(contact_id);
		
	}

	private void addItems(String contactId) {
		String numberPhone = getPhoneNumber(contactId);
		List<MessageSMS> listSms = messageDAO.getAllMessagesFromPhoneNumber(numberPhone);
		Iterator<MessageSMS> it = listSms.iterator();
		while(it.hasNext())
		{
			MessageSMS sms = it.next();
			Integer type = sms.getType();
			if(type.equals(MessageSMS.MESSAGE_TYPE_INBOX))
			{
				adapter.add(new OneComment(true, sms.getBody()));
			}
			else
			{
				adapter.add(new OneComment(false, sms.getBody()));
			}
		}
		adapter.notifyDataSetChanged();

	}
	private String getPhoneNumber(String contactId)
	{
		Contact contact = contactDAO.getContact(Integer.parseInt(contactId));
		String numberPhone = "";
		if(!contact.equals(null))
		{
			numberPhone = contact.getPhone_number();
		}
		
		return numberPhone;
	}
	private void sendSMS(String message, String number_phone)
	{
		String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";
 
        PendingIntent sentPI = PendingIntent.getBroadcast(context, 0,
            new Intent(SENT), 0);
 
        PendingIntent deliveredPI = PendingIntent.getBroadcast(context, 0,
            new Intent(DELIVERED), 0);
        //save message to db
        MessageSMS smsSave = new MessageSMS();
        smsSave.setAddress(number_phone);
        smsSave.setBody(message);
        smsSave.setDate(System.currentTimeMillis());
        smsSave.setStatus(-1);
        smsSave.setRead(MessageSMS.MESSAGE_IS_READ);
        smsSave.setSeen(MessageSMS.MESSAGE_IS_SEEN);
        smsSave.setType(MessageSMS.MESSAGE_TYPE_SENT);
		messageDAO.addMessage(smsSave);
        //send message
		SmsManager sms = SmsManager.getDefault();
		sms.sendTextMessage(number_phone, null, message, sentPI, deliveredPI); 
	}

}